package com.ttc.mBackup.BackupAgent;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.ttc.mBackup.BackupActivity;
import com.ttc.mBackup.R;
import com.ttc.mBackup.common.uploaddropbox;

public class BARAddTask extends Activity implements OnClickListener{

	/*
	 * Verify whattask and where you get or put backup file
	 * _ToTask hold int value 0,1,2 match with id of where your file
	 * _WhichTask hold boolean value with True is BackupTask, False is Resotre
	 * */
	//private int _TOTask;
	private boolean _WhichTask;
	/*ProgressDialog*/
	private ProgressDialog _progress;
	//Save name of file and Index
private	ArrayList<listviewlocal> model= new ArrayList<listviewlocal>();
	private int _index=0;
	
	/*get data send from Location Selector*/
	Bundle data;
	/*Save Dir of LsitFile*/
	private String dirfile;
	/*
	 * Create widget to show information and list to do
	 * */
	TextView name,detail;
	ImageView ig,download,upload;
	ListView lv;
/*For Dialog Progress....*/	
private static	 ProgressDialog _proDialog;
	//Task to do for Dialog
	int selector=0;

private	final ActionItem _replace = new ActionItem();
private	final ActionItem _delete= new ActionItem();

private	final ActionItem _upload = new ActionItem();
private	final ActionItem _restore=new ActionItem();
private QuickAction qa;
private ArrayList<String> listsys = new ArrayList<String>();	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.barlocal);

		/*List View */
		lv =(ListView) findViewById(R.id.list_local);
		download = (ImageView) findViewById(R.id.image_down);
		upload = (ImageView) findViewById(R.id.image_up);
		
		download.setVisibility(8);
		/*Receive Data*/
		data = getIntent().getExtras();
		if(data!=null)
		{
			
			_WhichTask = data.getBoolean(BackupActivity.KEY_ACTIVITY);
			AddWidget(_WhichTask,data);
			dirfile=data.getString(BARLocaltion.DIR_CHOICE);
			lv.setAdapter(setItemList(dirfile));
				
		
		}
		/*Upload all file in your Dir*/
		upload.setOnClickListener(this);
		
		/*
		 * Set Action Item of QuickActionDialog for ListView 
		 * */
		
	
		setforActionItem();
		
		/*Set on Item Click Listenner  for list View*/
		lv.setOnItemClickListener( new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				_index=arg2;
				
				qa = new QuickAction(arg1);
				if(_WhichTask)
				{
					
					
					qa.addActionItem(_replace);
					
				}
				else
				{
				qa.addActionItem(_restore);	
				}
				qa.addActionItem(_upload);
				qa.addActionItem(_delete);
				qa.setAnimStyle(QuickAction.ANIM_AUTO);
				
				qa.show();
				//CreateDialog(_WhichTask,false,
					//	data.getCharSequence(BARLocaltion.DIR_CHOICE).toString());
				
			}
		});
		
		
	}

/*
 * AddWidget() method : set text for textview, set value for visibility 
 * check var hold what type of your task : Backup or Restore
 * data hold some input data send by previuos activity
 * */	
	private void AddWidget(boolean check, final Bundle data)
	{
		name = (TextView) findViewById(R.id.title_local);
		detail = (TextView) findViewById(R.id.detail_local);
		ig = (ImageView) findViewById(R.id.image_add);
	
		
		if(check)
		{
		name.setText("BACKUP");
		detail.setText("Create or Replace your task to backup");
		ig.setVisibility(0);
		/*Call Dialog Task*/
		ig.setOnClickListener(this);
		
		}
		else
		{
			name.setText("RESTORE");
			detail.setText("Perform your task to Restore");
		}
		
		
	}
	
	/*
	 * Show file backup in folder have Directory dir
	 * */
	
	private ListLocaltion setItemList(String dir)
	{
		model.clear();
	File file = new File(dir);
		File[] listfile = file.listFiles();
		for(int i =0;i<listfile.length;i++)
			{
				model.add(new listviewlocal(listfile[i].getName(),
					R.drawable.androidicon,
					new  DateFormat().format("dd-MM-yyyy h:mmaa ",
						new  Date(listfile[i].lastModified())).toString()));
			}
		
		
		
		
		ListLocaltion adapter = new ListLocaltion(model);
		return adapter;
	}
	
	/*Create Input Dialog to put name of backup file
	 *  and call next Activity to choose what you wanna backup */
	@SuppressWarnings({ "static-access", "static-access", "static-access" })
	
	private void CreateDialog(boolean whichtask, String dir)
	{
		/*
		 * dirs hold directory to save file
		 * task hold boolean values : Backup- true, Restore - false
		 * one hold boolean values : Create - true or Replace - false
		 * 
		 * Create AlertDialog alert 
		 * Create View EditText and  TextView 
		  */
		
		final String dirs = dir ;
		final boolean task=whichtask;
		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		final EditText input = new EditText(this);
		
		
		/*
		 * one hold boolean values : Create - true or Replace - false
		 * check if is Create : put view Edittext into Dialog and settext is 
		 * date in format for it
		 * or not, put TextView and set text for it ... Set some condition if is backup
		 * we replce or restores we overiding...
		 * */
		input.setText(new DateFormat().format("ddMMyyyy", new Date()));
		alert.setView(input);
		alert.setIcon(R.drawable.erroricon);
		alert.setTitle("Name of Task")
		.setPositiveButton("Continue",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				
				String value = input.getText().toString().trim();
				/*Send Data and Call BARSelector activity */
				Intent i = new Intent("com.ttc.mBackup.BackupAgent.BARSELECTOR");
				Bundle extras = new Bundle();
				extras.putString(BARLocaltion.DIR_CHOICE, dirs);
				extras.putBoolean(BackupActivity.KEY_ACTIVITY, task);
				//Toast.makeText(getBaseContext(), one?value:model[_index].getName(), Toast.LENGTH_SHORT).show();
				extras.putString("FILE_NAME", value);
				extras.putStringArrayList(BARSelector.KEY_ELEMENT_SYSTEM, listsys);
				i.putExtras(extras);
				startActivity(i);
				dialog.dismiss();
			}	
		});
		alert.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
					}
				});
		AlertDialog dialog = alert.create();
		dialog.show();
	}

	/**Update adater of listview when done any job*/
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	File data = new File("data/data/com.ttc.mBackup/databases/"+DBAdapter.DATABASE_NAME);
        data.delete();
        lv.setAdapter(setItemList(dirfile));
	}
/*To dismis Dialog*/
	public static void upResult(boolean uples)
	{
		_proDialog.dismiss();
	}



	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		ImageView ig = (ImageView) v;
		
		switch (ig.getId()) {
		case R.id.image_add:	CreateDialog(true,data.getCharSequence(BARLocaltion.DIR_CHOICE).toString());
			
			break;

		case R.id.image_up:
			
			_proDialog = ProgressDialog.show(BARAddTask.this,"" , "Please Wait a few second.....");
			 SharedPreferences	pref= getSharedPreferences(
						LoginDropbox.ACCOUNT_PREFS_NAME, MODE_WORLD_WRITEABLE);
			 if(pref.getBoolean(LoginDropbox.LOG_DROPBOX, false)){
				 
				uploaddropbox upload= new uploaddropbox(getBaseContext(),new File(data.getCharSequence(BARLocaltion.DIR_CHOICE).toString())
															,pref.getString(LoginDropbox.ACCOUNT_DROPBOX,"" )
															,pref.getString(LoginDropbox.PASSWORD_DROPBOX,"" )
															,"/BackupSystems");
				upload.execute();
				
			 }
			break;
		}
		
			
		}
	
	/*
	 * Set Icon, Title, and Onclick Listener
	 * */
	private void setforActionItem()
	{
		/*Replace ActionItem*/
		_replace.setTitle("Replace");
		_replace.setIcon(getResources().getDrawable(R.drawable.replaceicon));
		_replace.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent("com.ttc.mBackup.BackupAgent.BARSELECTOR");
				Bundle extras = new Bundle();
				extras.putString(BARLocaltion.DIR_CHOICE, dirfile);
				extras.putBoolean(BackupActivity.KEY_ACTIVITY, _WhichTask);
				//Toast.makeText(getBaseContext(), one?value:model[_index].getName(), Toast.LENGTH_SHORT).show();
				extras.putString("FILE_NAME",model.get(_index).getName());
				
				i.putExtras(extras);
				qa.dismiss();
				startActivity(i);
			}
		});
		
		/*Restore ActionItem*/
		_restore.setTitle("Restore");
		_restore.setIcon(getResources().getDrawable(R.drawable.driveicon));
		_restore.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i = new Intent("com.ttc.mBackup.BackupAgent.BARSELECTOR");
				Bundle extras = new Bundle();
				extras.putString(BARLocaltion.DIR_CHOICE, dirfile);
				extras.putBoolean(BackupActivity.KEY_ACTIVITY, _WhichTask);
				//Toast.makeText(getBaseContext(), one?value:model[_index].getName(), Toast.LENGTH_SHORT).show();
				extras.putString("FILE_NAME",model.get(_index).getName());
				
				i.putExtras(extras);
				qa.dismiss();
				startActivity(i);
			}
		});
		
		/*Upload ActionItem*/
		_upload.setTitle("Upload");
		_upload.setIcon(getResources().getDrawable(R.drawable.uploadicon));
		_upload.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				/**/
				_proDialog = ProgressDialog.show(BARAddTask.this,"" , "Please Wait a few second.....");
				
		//	Toast.makeText(getBaseContext(),dirfile+model.get(_index), Toast.LENGTH_LONG ).show();
			
				SharedPreferences	pref= getSharedPreferences(
						LoginDropbox.ACCOUNT_PREFS_NAME, MODE_WORLD_WRITEABLE);
			 if(pref.getBoolean(LoginDropbox.LOG_DROPBOX, false)){
				 
				uploaddropbox upload= new uploaddropbox(getBaseContext(),new File(dirfile+File.separator+model.get(_index).getName())
															,pref.getString(LoginDropbox.ACCOUNT_DROPBOX,"" )
															,pref.getString(LoginDropbox.PASSWORD_DROPBOX,"" )
															,"/BackupSystems");
				upload.execute();
				
			 }
			 else
			 {
				 
				 Intent login = new Intent("com.ttc.mBackup.BackupAgent.LOGINDROPBOX");
				 startActivity(login);
				 _proDialog.dismiss();
				 qa.dismiss();
			 }
			}
		});
		
		/*Delete*/
		_delete.setTitle("Delete");
		_delete.setIcon(getResources().getDrawable(R.drawable.deleteicon));
		_delete.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				File delfile = new File(dirfile+File.separator+model.get(_index).getName());
				delfile.delete();
				model.remove(_index);
				lv.setAdapter(setItemList(dirfile));
				qa.dismiss();
			}
		});
	}
	}

	

